import { $toClass, $trimAll } from "./main";
// vuex载入函数
/* 
	$__model(state:Object,params:Object,{
		sess:Object
		,sessAuto:Boolean
	})
*/
function $__model(state, params, { sess, sessAuto }) {
	if (params) {
		if ($toClass(params) == "Object") {
			Object.keys(params).forEach((keys) => {
				let value = params[keys];
				let modelArr = $trimAll(keys).split(/[,|]/);
				modelArr.forEach((child) => {
					let serChild = child.replace(/(\[)|(\])/g, (match, p1, p2) => {
						if (p1) {
							return ".";
						} else if (p2) {
							return "";
						} else {
							return match;
						}
					});
					let modelLeveArr = serChild.split(".");
					let copyState = state;
					for (let index = 0, leveLen = modelLeveArr.length; index < leveLen; index++) {
						let leveKey = modelLeveArr[index];
						if (leveKey) {
							let leveObj = copyState[leveKey];
							if (index == leveLen - 1) {
								copyState[leveKey] = value;
								break;
							} else {
								copyState = leveObj;
							}
						}
					}
				});
			});
			if (sessAuto) {
				sess.state = JSON.stringify(state);
			}
		} else {
			throw new TypeError('the params must be Object ');
		}
	} else {
		throw ReferenceError('the params is required');
	}
}

// vuex 提交函数
/* 
	$commit(params:Object)
*/
function $commit(params) {
	if (params) {
		this.$store.commit('$model', params);
	} else {
		throw new ReferenceError('the params is must required');
	}
}

export {
	$__model
	, $commit
}